<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * File Storage Class
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	File Storage
 * @version		1.0
 * @author		Matthew Glinski
 * @link		---- Not Yet Documented or Hosted ----
 */
 
class CI_Storage
{
	public $storagePath = './store';
	public $CI;
	
	function CI_Storage()
	{
		$this->CI =& get_instance();
	}
	
	function getStoredFileLocation($id, $store='')
	{
		if(!$store)
		{
			$query = $this->db->get_where('store', array('file_id' => $id));
			
			if(!$query->num_rows())
			{
				return false;
			}
			
			$store = $query->row();
		}
		
		return $this->storagePath.'/'.$store->prefix.'/'.$store->filename;
	}
	
	function getStoredFileInfo($id)
	{
		$query = $this->db->get_where('store', array('file_id' => $file));
		return $query->row();
	}
	
	function getFileID($file)
	{
		$query = $this->CI->db->get_where('store', array('id' => $file));
		$store = $query->row();
		
		return $store->file_id;
	}
	
	function saveFileToStore($file)
	{
		$md5 = md5_file($file);
		$size = filesize($file);
		$file_id = $this->_genFileId();
		
		$prefix = substr($md5,0,2);
		
		$new_path = $this->storagePath.'/'.$prefix.'/'.basename($file);
		
		if(!is_dir($this->storagePath.'/'.$prefix))
		{
			mkdir($this->storagePath.'/'.$prefix);
		}
		
		if(is_uploaded_file($file))
		{
			move_uploaded_file($file, $new_path);
		}
		else
		{
			rename($file, $new_path);
		}
		
		$data = array(
			'o_filename' => basename($file), 
			'filename' => $new_path,
			'size' => $size,
			'md5' => $md5,
			'file_id' => $file_id,
			'status' => 1,
			'type' => str_replace('.','',strtolower(strrchr(basename($file), '.'))),
			'ip' => $_SERVER['REMOTE_ADDR'],
			'prefix' => $prefix,
			'time' => time()
		);
		
		$this->CI->db->insert('store', $data);
		
		return $file_id;
	}
	
	function deleteStoredFile($id)
	{
		unlink($this->getStoredFileLocation($id));
		$this->CI->db->delete('store', array('file_id' => $id));
		return true;
	}
	
	function _doesStoredFileExist($id)
	{
		return file_exists($this->getStoredFileLocation($id));
	}
	
	function _getFileMD5($file)
	{
		if(!$this->_doesStoredFileExist($this->getFileID($file)))
			return false;
		
		return md5_file($file);
	}
	
	function _genFileId()
	{
		$password = "";
		
		$vals = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabchefghjkmnpqrstuvwxyz0123456789_-'; 
		
		$length = 16;
		while (strlen($password) < $length) 
		{
			mt_getrandmax();
			$num = rand() % strlen($vals);
			$password .= substr($vals, $num+4, 1);
		}
		return $password;
	}
}?>